local filename = "setagencyrid.lua"

local timetool = require "timetool"
local skynet = require "skynet"
local cluster = require "skynet.cluster"
local filelog =require "filelog"
require "pubenum"

local service = nil
local CMD = {
	service = nil
}

--
--设置代理rid
--
function CMD.process(rid, msgbody)
	if not service then
		service = CMD.service
	end

    if not msgbody.agencyrid or tonumber(msgbody.agencyrid) < 0 then
        return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "该代理不存在"}
    end

    --检测是否已有代理
    if service.info.agencyrid and tonumber(service.info.agencyrid) > 0 then
        return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "已经设置过代理"}
    end

    --代理不能为自己
    if rid == tonumber(msgbody.agencyrid) then
        return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "不能设置代理为自己"}
    end

    -- 去数据节点查询该代理rid是否存在
    local agencylevel = 0
    local agencyrid =  tonumber(msgbody.agencyrid) or 0
	local result = cluster.call("datanode", ".router", "select_rk", agencyrid, "rs_info", true)
	if result and result[1] ~= 0 then
		agencylevel = result[2][agencyrid].agencylevel
	else
        return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "该代理不存在"}
    end

	service.info.agencyrid = agencyrid
	result = cluster.call("datanode", ".router", "update_rk", rid, "rs_info", 0, msgbody)

	return {}
end

return CMD
